package com.jt.tenant.widget;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import com.jt.tenant.R;
import com.jt.tenant.activity.MainActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/4/25.
 */

public class UpdateService extends Service {

    private String file_real_name;

    private String size="0";

    //文件存储
    private File updateDir = null;

    private File updateFile = null;

    private String num = "";

    private int aa = 0;

    private Handler updateHandler = new  Handler(){

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 0x11:

                    String tip=(String) msg.obj;

                    Toast.makeText(UpdateService.this, tip, Toast.LENGTH_SHORT).show();

                    break;

                case 0x22:

                    String tip1=(String) msg.obj;

                    Toast.makeText(UpdateService.this, tip1,Toast.LENGTH_SHORT).show();

                    break;
                case 0x33:

                    updateNotification = new Notification.Builder(UpdateService.this)
                            .setAutoCancel(true)
                            .setContentTitle("优路兔")
                            .setContentText("正在下载"+num)
                            .setContentIntent(updatePendingIntent)
                            .setSmallIcon(R.mipmap.logo_bcb)
                            .setWhen(System.currentTimeMillis())
                            .build();

                    updateNotificationManager.notify( 105, updateNotification);


                    break;

            }
        }
    };

    //通知栏
    private NotificationManager updateNotificationManager = null;

    private Notification updateNotification = null;

    //通知栏跳转Intent

    private Intent updateIntent = null;

    private PendingIntent updatePendingIntent = null;

    private NotificationCompat.Builder mBuilder;

    @Override
    public IBinder onBind(Intent intent) {

        return null;

    }

    @SuppressWarnings("deprecation")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //获取传值
        file_real_name=intent.getStringExtra("file_real_name");

        final String down_url=intent.getStringExtra("DownloadPath");

        //创建文件
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){

            updateDir = new File(Environment.getExternalStorageDirectory()+"/jt");

            updateFile = new File(updateDir.getPath()+"/"+file_real_name);

        }

        updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

//        updateNotification = new Notification();

        //设置下载过程中，点击通知栏，回到主界面
        updateIntent = new Intent(this,MainActivity.class);

        updatePendingIntent = PendingIntent.getActivity(this,  0,updateIntent,  0);

        //设置通知栏显示内容
//        updateNotification.icon = R.mipmap.logo_bcb;
//
//        updateNotification.tickerText = "开始下载";

        mBuilder = new NotificationCompat.Builder(this);

//        updateNotification = new Notification.Builder(this)
        mBuilder
                .setAutoCancel(true)
                .setContentTitle("优路兔")
                .setContentText("正在下载0%")
                .setContentIntent(updatePendingIntent)
                .setSmallIcon(R.mipmap.logo_bcb)
                .setWhen(System.currentTimeMillis())
                ;


//        updateNotification.setLatestEventInfo(this, "简途", "0%", updatePendingIntent);

        //发出通知
        updateNotificationManager.notify(105,mBuilder.build());

        //开启一个新的线程下载，如果使用Service同步下载，会导致ANR问题，Service本身也会阻塞
        new Thread(){

            public void run() {

                try {

                    //增加权限;
                    if(!updateDir.exists()){

                        updateDir.mkdirs();

                    }

                    if(!updateFile.exists()){

                        updateFile.createNewFile();

                    }

                    long downloadSize = downloadUpdateFile(down_url,updateFile);

                    if(downloadSize>  0){

//                      //下载成功
                        Message message=Message.obtain();

                        message.what=0x11;

                        message.obj="下载成功";

                        updateHandler.sendMessage(message);

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                    Message message=Message.obtain();

                    message.what = 0x22;

                    //下载失败
                    updateHandler.sendMessage(message);
                }

            };

        }.start();

        return super.onStartCommand(intent, flags, startId);
    }



    @SuppressWarnings("deprecation")
    public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {

        int downloadCount =   0;

        int currentSize =   0;

        long totalSize =   0;

        int updateTotalSize = Integer.parseInt(size);

        HttpURLConnection httpConnection = null;

        InputStream is = null;

        FileOutputStream fos = null;

        try {

            URL url = new URL(downloadUrl);

            httpConnection = (HttpURLConnection)url.openConnection();

            size = httpConnection.getContentLength()+ "";

            updateTotalSize = Integer.parseInt(size);

            httpConnection.setConnectTimeout(1000);

            httpConnection.setReadTimeout(2000);

            if (httpConnection.getResponseCode() == 200) {

                is = httpConnection.getInputStream();

                fos = new FileOutputStream(saveFile, false);

                byte buffer[] = new byte[1024];

                int readsize =   0;

                while((readsize = is.read(buffer)) >   0){

                    fos.write(buffer,   0, readsize);

                    totalSize += readsize;

                    System.out.println(totalSize);

                    int num = (int)((totalSize*100)/updateTotalSize);
                        if((downloadCount ==   0)||(int) (totalSize*100/updateTotalSize)<=1){
//                        downloadCount +=   1;

                            if(aa!=num){

                                mBuilder.setContentText("正在下载" + num+"%");
                                updateNotificationManager.notify(105, mBuilder.build());
                                aa= num;

                            }

                    }

                }

                fos.flush();

//                updateNotification.setLatestEventInfo(UpdateService.this, "下载完成", (int)totalSize*100/updateTotalSize+"%", updatePendingIntent);

                Intent installIntent = new Intent(Intent.ACTION_VIEW);

                Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/jt/" + file_real_name));

                installIntent.setDataAndType(uri,
                        "application/vnd.android.package-archive");
                installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                TaskStackBuilder stackBuilder=TaskStackBuilder.create(getApplicationContext());

                stackBuilder.addParentStack(MainActivity.class);

                Intent intent=new Intent(getApplicationContext(), MainActivity.class);

                stackBuilder.addNextIntent(intent);

                PendingIntent pendingIntent=stackBuilder.getPendingIntent(  0, PendingIntent.FLAG_UPDATE_CURRENT);

//                updateNotification.contentIntent=pendingIntent;
//
//                updateNotificationManager.notify(  0, updateNotification);
//
                updateNotificationManager.cancelAll();

                // 震动提示
                Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

                vibrator.vibrate(1000L);// 参数是震动时间(long类型)

                stopSelf();

                startActivity(installIntent);

            }else{

                Message message=Message.obtain();

                message.obj="网络请求失败";

                message.what=0x111;

                updateHandler.sendMessage(message);

            }
        }catch(Exception exception){

            exception.printStackTrace();

        } finally {

            if(httpConnection != null) {

                httpConnection.disconnect();

            }

            if(is != null) {

                is.close();

            }
            if(fos != null) {

                fos.close();

            }

        }

        return totalSize;

    }
}
